/*
 * @Description:
 * @Author: dh
 * @Date: 2022-01-21 13:41:19
 * @LastEditors: dh
 * @LastEditTime: 2022-07-18 10:55:32
 */
import { ref, watch } from 'vue';

interface Range {
	min?: number;
	max?: number;
}
/**
 * @description:
 * @param {number} initialVal 数字初始值
 * @param {Range} range 数字范围
 * @return {*}
 */
export default function useCount(initialVal: number, range?: Range) {
	const current = ref(initialVal);
	/* 增加 */
	const inc = (value?: number): void => {
		if (typeof value === 'number') {
			current.value += value;
		} else {
			current.value += 1;
		}
	};
	/* 减少 */
	const dec = (value?: number): void => {
		if (typeof value === 'number') {
			current.value -= value;
		} else {
			current.value -= 1;
		}
	};
	/* 设置 */
	const set = (value?: number): void => {
		if (typeof value === 'number') {
			current.value -= value;
		}
	};
	/* 重置 */
	const reset = () => {
		current.value = initialVal;
	};
	/* 监听 */
	watch(current, (newVal: number, oldVal: number) => {
		if (newVal === oldVal) return;
		if (range && range.min && newVal < range.min) {
			current.value = range.min;
		} else if (range && range.max && newVal > range.max) {
			current.value = range.max;
		}
	});

	return {
		current,
		inc,
		dec,
		set,
		reset,
	};
}
